package com.lxd.milktea.service.impl;
import com.lxd.milktea.converter.OrderMasterToOrderDTOConverter;
import com.lxd.milktea.dao.OrderDetailRepository;
import com.lxd.milktea.dao.OrderMasterRepository;
import com.lxd.milktea.dataobject.OrderDetail;
import com.lxd.milktea.dataobject.OrderMaster;
import com.lxd.milktea.dataobject.ProductInfo;
import com.lxd.milktea.dto.CartDTO;
import com.lxd.milktea.dto.OrderDTO;
import com.lxd.milktea.enums.ResultEnum;
import com.lxd.milktea.exception.SellException;
import com.lxd.milktea.service.OrderService;
import com.lxd.milktea.service.ProductService;
import com.lxd.milktea.util.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 2017-12-10 16:44
 * @author carrymaniac
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    private final OrderDetailRepository orderDetailRepository;

    private final OrderMasterRepository orderMasterRepository;

    private final ProductService productService;

    public OrderServiceImpl(OrderDetailRepository orderDetailRepository, OrderMasterRepository orderMasterRepository, ProductService productService) {
        this.orderDetailRepository = orderDetailRepository;
        this.orderMasterRepository = orderMasterRepository;
        this.productService = productService;
    }

    @Override
    public OrderDTO create(OrderDTO orderDTO) {
        String orderId =KeyUtil.genUniqueKey();
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        //1.查询商品(数量,价格)
        for(OrderDetail orderDetail : orderDTO.getOrderDetailList()){
            ProductInfo one = productService.findOne(orderDetail.getProductId());
            if(one == null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //2.计算总价
            orderAmount = one.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);
            //订单详情入库
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(one,orderDetail);
            OrderDetail save = orderDetailRepository.save(orderDetail);
            log.info("{订单详情入数据库}"+save);
        }

        //3.写入订单数据库(orderMaster,OrderDetail)
        OrderMaster orderMaster = new OrderMaster();
        //注意 要先拷贝 否则为null的值也会被覆盖进去
        BeanUtils.copyProperties(orderDTO,orderMaster);
        //原本初始化的状态也被覆盖了
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);
        orderMasterRepository.save(orderMaster);
        //4.扣库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e ->
                new CartDTO(e.getProductId(), e.getProductQuantity())
        ).collect(Collectors.toList());
        productService.decreaseStock(cartDTOList);
        return orderDTO;
        }

    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        Page<OrderMaster> byBuyerOpenid = orderMasterRepository.findAll(pageable);
        List<OrderDTO> convert = OrderMasterToOrderDTOConverter.convert(byBuyerOpenid.getContent());
        return new PageImpl<>(convert,pageable,byBuyerOpenid.getTotalElements());
    }

    @Override
    public OrderDTO findOne(String orderID) {
        Optional<OrderMaster> optional = orderMasterRepository.findById(orderID);
        if(!optional.isPresent()){
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }else {
            OrderMaster orderMaster = optional.get();
            List<OrderDetail> byOrOrderId = orderDetailRepository.findByOrderId(orderID);
            if(CollectionUtils.isEmpty(byOrOrderId)){
                throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
            }
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(orderMaster,orderDTO);
            orderDTO.setOrderDetailList(byOrOrderId);
            return orderDTO;
        }
    }

    @Override
    public List<OrderDetail> findListByDate(Timestamp createTime) {
        return orderDetailRepository.findByCreateTimeAfter(createTime);
    }


}
